package com.autonavi.yunda.yunji.service;

import com.autonavi.yunda.yunji.core.engine.script.FunctionScriptClassManager;
import com.autonavi.yunda.yunji.core.service.IFunctionConfigService;
import com.autonavi.yunda.yunji.core.vo.EngineFunctionConfigVO;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.autonavi.yunda.yunji.core.config.EngineConstant.FUNCTION_VERSION_SEPARATOR;

/**
 * @author cizhong.wcs
 * @date 2023/8/31 17:08
 */
@Component
public class FunctionConfigService implements IFunctionConfigService {

    @Override
    public EngineFunctionConfigVO findEngineFunctionConfigVO(String functionName, String functionVersion) {
        return FileLoaderService.functionConfigVOS.stream()
                .filter(vo -> vo.getVersion().equals(functionVersion) && vo.getName().equals(functionName))
                .findFirst().orElse(null);
    }

    @Override
    public List<Pair<String, String>> listNewPublishedFunction(List<Pair<String, String>> existsFunctionNameVersion) {
        List<Pair<String, String>> collect = new ArrayList<>();
        if (existsFunctionNameVersion.isEmpty()) {
            collect.addAll(FileLoaderService.functionConfigVOS.stream()
                    .map(vo -> Pair.of(vo.getName(), vo.getVersion()))
                    .collect(Collectors.toList()));
        } else {
            List<String> keyList = existsFunctionNameVersion.stream()
                    .map(p -> p.getLeft() + FUNCTION_VERSION_SEPARATOR + p.getRight()).collect(Collectors.toList());
            keyList.forEach(key -> {
                if (!FunctionScriptClassManager.functionScriptClassMap.containsKey(key)) {
                    collect.add(Pair.of(key.split(FUNCTION_VERSION_SEPARATOR)[0], key.split(FUNCTION_VERSION_SEPARATOR)[1]));
                }
            });
        }
        return collect;
    }

}
